//
//  PhotoBrowserViewController.swift
//  新浪微博
//
//  Created by 焦林生 on 15/11/18.
//  Copyright © 2015年 焦林生. All rights reserved.
//

import UIKit
import SVProgressHUD

//定义可重用标示符
private let PhotoBrowserViewCellID = "PhotoBrowserViewCellID"

//照片查看视图控制器
class PhotoBrowserViewController: UIViewController {

    //图像URL数组
    var urls: [NSURL]
     //选中照片索引
    var selectedIndexPath: NSIndexPath
    
    
    //MARK: 构造函数
    init(urls: [NSURL], indexPath: NSIndexPath) {
    
        self.urls = urls
        
        self.selectedIndexPath = indexPath
        
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: 懒加载控件
    //collectionView
     lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero,
        collectionViewLayout: PhotoBrowserViewLayout())
    
    //关闭按钮
    private lazy var closeButton: UIButton = UIButton(title: "关闭", fontSize: 14,
        color: UIColor.whiteColor(),
        imageName: nil,
        backColor: UIColor.darkGrayColor())
    
    //保存按钮
    private lazy var saveButton: UIButton = UIButton(title: "保存", fontSize: 14,
        color: UIColor.whiteColor(),
        imageName: nil,
        backColor: UIColor.darkGrayColor())
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //设置选中照片
        collectionView.scrollToItemAtIndexPath(selectedIndexPath, atScrollPosition: .CenteredHorizontally, animated: false)
    }
    //MARK: 设置界面
    override func loadView() {
        var rect = UIScreen.mainScreen().bounds
        
        rect.size.width += 20
        
        view = UIView(frame: rect)
        
        setupUI()
    }
    
    //MARK: 监听方法
    //关闭
   @objc private func close() {
    
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //保存图片
   @objc private func save() {
    
        guard let image = (collectionView.visibleCells().last as? PhotoBrowserCell)?.imageView.image else {
        
            print("没有图像")
            return
        }
    
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    
    @objc private func image(image:UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject?){
    
        let message = error != nil ? "保存失败" : "保存成功"
        
        SVProgressHUD.showInfoWithStatus(message)
    }
    
    //MARK: 自定义流水布局
    private class PhotoBrowserViewLayout: UICollectionViewFlowLayout {
    
        private override func prepareLayout() {
            super.prepareLayout()
            
            itemSize = collectionView!.bounds.size
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            scrollDirection = .Horizontal
            
            collectionView?.pagingEnabled = true
            collectionView?.bounces  = false
            collectionView?.showsHorizontalScrollIndicator = false
        }
    }
    

}

// MARK: - 设置界面
private extension PhotoBrowserViewController {

    private func setupUI() {
    
        //1 添加控件
        view.addSubview(collectionView)
        view.addSubview(closeButton)
        view.addSubview(saveButton)
        
        //2 控件布局
        collectionView.frame = view.bounds
        
        closeButton.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(-8)
            make.left.equalTo(view.snp_left).offset(8)
            make.size.equalTo(CGSize(width: 100, height: 36))
        }
        
        saveButton.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(-8)
            make.right.equalTo(view.snp_right).offset(-28)
            make.size.equalTo(CGSize(width: 100, height: 36))
        }
        
        //3 添加按钮监听方法
        closeButton.addTarget(self, action: "close", forControlEvents: .TouchUpInside)
        saveButton.addTarget(self, action: "save", forControlEvents: .TouchUpInside)
        
        //4 准备控件
        prepareCollectionView()
    }
    
    //准备collectionView
    private func prepareCollectionView() {
    
        //1 设置数据源
        collectionView.dataSource = self
        
        //2 注册可充cell
        collectionView.registerClass(PhotoBrowserCell.self, forCellWithReuseIdentifier: PhotoBrowserViewCellID)
    }
}
// MARK: - UICollectionViewDataSource
extension PhotoBrowserViewController: UICollectionViewDataSource {

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return urls.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PhotoBrowserViewCellID, forIndexPath: indexPath) as! PhotoBrowserCell
        

        cell.imageURL = urls[indexPath.item]
        //设置代理
        cell.photoDelegate = self
        
        return cell
    }
}

// MARK: - PhotoBrowserCellDelegate
extension PhotoBrowserViewController: PhotoBrowserCellDelegate {

    func photoBrowserCellShouldDismiss() {
        
        close()
    }
    
    //图像视图缩放
    func photoBrowserCellDidZoom(scale: CGFloat) {
    
        //0 是否交互
        let startInteraction = scale < 1.0
        
        //1 隐藏控件
        hiddenControls(startInteraction)
        
        //2 判断是否缩放视图
        if startInteraction {
        
            view.alpha = scale
            view.transform = CGAffineTransformMakeScale(scale, scale)
        } else {
        
            view.alpha = 1
            view.transform = CGAffineTransformIdentity
        }
    }
    
    //隐藏控件
    private func hiddenControls(isHidden: Bool) {
    
        closeButton.hidden = isHidden
        saveButton.hidden = isHidden
        
        collectionView.backgroundColor = isHidden ? UIColor.clearColor() : UIColor.blackColor()
    }
}
// MARK: - PhotoBrowserDismissDelegate
extension PhotoBrowserViewController: PhotoBrowserDismissDelegate {

    
    func imageViewForDismiss() -> UIImageView {
        let iv = UIImageView()
        
        iv.contentMode = .ScaleAspectFill
        iv.clipsToBounds = true
        
        let cell = collectionView.visibleCells()[0] as! PhotoBrowserCell
        
        iv.image = cell.imageView.image
        iv.frame = cell.scrollView.convertRect(cell.imageView.frame,
            toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        return iv
    }
    
    func indexPathForDismiss() -> NSIndexPath {
        return collectionView.indexPathsForVisibleItems()[0]
    }
}



